package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.Travel;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.query.TravelQueryObject;
import cn.wolfcode.trip.base.service.ITravelService;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

//该项目是符合REST规范的,此时该控制器表示操作用户的资源
@RestController //Controller+ResponseBody
@RequestMapping("/users")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private ITravelService travelService;

    /*
    更新某个用户的游记
    资源:/users/{authorId}/travels
    动作:PUT
    参数:很多...(参考数据库表)
     */
    @PutMapping("/{authorId}/travels")
    public Object updateTravels(Travel entity) {
        travelService.saveOrUpdate(entity);
        return new JSONResult();
    }

    /*
    保存某个用户的游记
    资源:/users/{authorId}/travels
    动作:POST
    参数:很多...(参考数据库表)
     */
    @PostMapping("/{authorId}/travels")
    public Object saveTravels(Travel entity) {
        //自动填充作者
        entity.setAuthor(UserContext.getCurrentUser());
        travelService.saveOrUpdate(entity);
        return new JSONResult();
    }

    /*
    获取某个用户的所有游记(带有分页功能)
    资源:/users/{authorId}/travels
    动作:GET
    参数:currentPage=x
     */
    @GetMapping("/{authorId}/travels")
    public Object queryTravel(TravelQueryObject qo) {
        //需要按照发布时间排序,这里设置下
        qo.setOrderBy("t.lastUpdateTime desc");
        qo.setState(null);
        PageInfo<Travel> info = travelService.queryTravel(qo);
        return info;
    }

    /*
        注册用户的接口
        资源:/users
        动作:POST
        参数:email=xx&nickName=xx&password=xx
     */
    @PostMapping
    public Object regist(User u) {
        JSONResult result = new JSONResult();
        try {
            //调用业务层注册的方法
            userService.regist(u);
            result.setData(u); //设置当前登录的用户,一起返回
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    /*
    更新用户信息
    资源:/users/{id}
    动作:PUT
    参数:nickName=xx&gender=xx&place=xx&sign=xx&headImgUrl=xx&coverImgUrl=xx
     */
    @PutMapping("/{id}")
    public Object updateUser(User u) {
        JSONResult result = new JSONResult();
        try {
            //调用业务层注册的方法
            userService.saveOrUpdate(u);
            result.setData(u); //设置当前登录的用户,一起返回
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }
}
